package com.java.util.javautil.scs.Multithreading;

import sun.misc.BASE64Decoder;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

public class ImgDataUrl {

    /**
     * 对Base64字符串解码并生成图片
     * @param imgStr
     * @param imgName
     * @param imgPath
     * @return
     */
    public static boolean GenerateImage(String imgStr, String imgName, String imgPath) {
        if (imgStr == null) {
            return false;
        }
        BASE64Decoder decoder = new BASE64Decoder();
        try {
            //Base64解码
            byte[] b = decoder.decodeBuffer(imgStr);
            for (int i = 0; i < b.length; ++i) {
                if (b[i] < 0) {
                    //调整异常数据
                    b[i] += 256;
                }
                File headPath = new File(imgPath);
                //判断文件夹是否创建，没有创建则创建新文件夹
                if (!headPath.exists()) {
                    headPath.mkdirs();
                }
                //定义图片路径
                String imgFilePath = imgPath + "\\" + imgName + ".png";
                //新生成的图片
                OutputStream out = new FileOutputStream(imgFilePath);
                out.write(b);
                out.flush();
                out.close();
                return true;
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return true;
    }


    public static void main(String[] args) {
        GenerateImage(""
                , "geekbang"
                , "G:\\Front-End\\day001\\demo01\\resource");
    }
}